import java.util.Date;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import com.java4less.rchart.Chart;
import com.java4less.rchart.ChartAdapter;
import com.java4less.rchart.ChartListener;
import com.java4less.rchart.ChartLoader;
import com.java4less.rchart.j2me.J2meCanvas;
import com.java4less.rchart.j2me.J2meViewer;
import com.java4less.rchart.util.Formats;

public class J4LChartMIDLet extends MIDlet implements CommandListener {
	
	  Display display;
	  Form mainForm;
	  StringItem progressItem;
	  StringItem label1;
	  StringItem result;
	  Command nextExample= new Command("Next example", Command.SCREEN, 1);
	  J2meViewer chartCanvas;
	  ChartLoader loader;
	  
	String[] examples={"MultiAxis.txt","combined2Positions.txt","patternFilling.txt","linechart.txt","barChart3D.txt","targetZones.txt","MultiCharts.txt","radarChart.txt","scatterChart.txt","areaChart.txt","areaCurves.txt","axisOnTop.txt","barChart.txt","barImages.txt","bubbleChart.txt","candleStick.txt",
			"combinedChart.txt","event.txt","gauge.txt","linechart3D.txt","lineChartClipping.txt","lineChartNULLS.txt",
			"pieChart2D.txt","piechart3D.txt","realtime.txt","stackedBar.txt",
			"StackedMultiAxis.txt"}; 
	int currentExample=0;
	
	// create chart listener 
	ChartAdapter chartAdapter=new ChartAdapter() {
					public void chartEvent(Chart c,int type) {
						if (type==ChartListener.EVENT_POINT_CLICKED) {
							System.out.println("You just clicked on series "+ c.selectedSerie.name.toUpperCase() + " point "+ (c.selectedSeriePoint+1));
						}
						
						if (type==ChartListener.EVENT_CHART_CLICKED) System.out.println("You just clicked on the chart but no objects are selected");
						
						// rebuild chart with new data
						if (type==ChartListener.EVENT_BEFORE_UPDATE) {
							// // get a new random value between 0 and 40 and update 3 of the values in the serie
							int newValue=(int) (System.currentTimeMillis() % 40); 
							c.plotters[0].getSerie(0).replaceYValueAt(1,newValue);
							c.plotters[0].getSerie(0).replaceYValueAt(2,newValue+10);
							c.plotters[0].getSerie(0).replaceYValueAt(3,newValue-10);							

							// do not allow the chart to be rebuilt from the original parameters
							c.autoRebuild=false;
							

						}						
						
					}
				};	
				
	// create chart listener for the drill down chart
	ChartAdapter chartAdapterDrillDown=new ChartAdapter() {
						public void chartEvent(Chart c,int type) {
							// load subchart
							if (type==ChartListener.EVENT_POINT_CLICKED) {		
								if (c.selectedSeriePoint==0) loadChartFromFile("subpie1.txt");
								else if (c.selectedSeriePoint==1) loadChartFromFile("subpie2.txt");
								else if (c.selectedSeriePoint==2) loadChartFromFile("subpie3.txt");		
							}						
						}
					};	
	
	// create chart listener for the drill down chart
	ChartAdapter chartAdapterRealtime=new ChartAdapter() {
						public void chartEvent(Chart c,int type) {
							// load subchart
							if (type==ChartListener.EVENT_BEFORE_UPDATE) createRealtimedata(loader);
						}
					};		
	
					

	public J4LChartMIDLet() {
		
		super();

		try {
		System.out.println("Creating...");
		mainForm = new Form (null);
		mainForm.setCommandListener(this);
		mainForm.addCommand(nextExample);
		System.out.println("Creating chart viewer...");		
		chartCanvas=new J2meViewer(null);
		chartCanvas.setPreferredChartSize(200,200);
		
		System.out.println("Creating chart ...");
		createDefaultChart();
		
		mainForm.append(chartCanvas);
		
		} catch (Throwable t) {
			t.printStackTrace();
		}

	}

	protected void startApp() throws MIDletStateChangeException {
		System.out.println("Starting...");
	   display = Display.getDisplay (this);
	   
	    display.setCurrent (mainForm);
		
			
	}

	protected void pauseApp() {

	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {

	}
	
	public void createDefaultChart() {

		System.out.println("Creating loader ...");

		ChartLoader cha=new ChartLoader();			
		cha.clearParams();				
		
		cha.setParameter("TITLECHART","Sales 2006");
		cha.setParameter("TITLE_FONT","Proportional|BOLD|12");
		cha.setParameter("LEGEND","NO");
		cha.setParameter("XSCALE_MIN","0");
		cha.setParameter("XSCALE_MAX","5.5");
		cha.setParameter("YSCALE_MIN","-15");
		cha.setParameter("BIG_TICK_INTERVALX","1");
		cha.setParameter("BIG_TICK_INTERVALY","1");
		cha.setParameter("TICK_INTERVALY","10");		
		cha.setParameter("XAXIS_LABELS","June| |Aug.| |Oct.| |Dec.");
		cha.setParameter("CERO_XAXIS","LINE");
		cha.setParameter("YAXIS_INTEGER","TRUE");
		cha.setParameter("SERIE_1","Products");
		cha.setParameter("SERIE_2","Services");
		cha.setParameter("SERIE_TYPE_1","BAR");
		cha.setParameter("SERIE_TYPE_2","BAR");
		cha.setParameter("SERIE_FONT_1","Arial|PLAIN|7");
		cha.setParameter("SERIE_FONT_2","Arial|BOLD|7");
		cha.setParameter("BOTTOM_MARGIN","0.18");
		cha.setParameter("LEFT_MARGIN","0.2");
		cha.setParameter("RIGHT_MARGIN","0");
		cha.setParameter("LEGEND_MARGIN","0");
		cha.setParameter("SERIE_DATA_2","-10|41|48|39|36");
		cha.setParameter("SERIE_BORDER_TYPE_1","RAISED");
		cha.setParameter("SERIE_BORDER_TYPE_2","RAISED");
		cha.setParameter("SERIE_BAR_STYLE_1","0xff00");
		cha.setParameter("SERIE_BAR_STYLE_2","0xff");
		cha.setParameter("BARCHART_BARSPACE","1");		
		cha.setParameter("CHART_FILL","0xffcc00");
		cha.setParameter("SERIE_NEGATIVE_STYLE_2","RED");
		cha.setParameter("YLABEL_VERTICAL","TRUE");
		cha.setParameter("SERIE_DATA_1","12|43|50|45|30");
		cha.setParameter("SERIE_TIPS_1","12|43|50|45|30");
		cha.setParameter("SERIE_TIPS_2","-10|41|48|39|36");
		cha.setParameter("CHART_SHOW_TIPS","true");
		cha.setParameter("BARCHART_BARSPACE","5");
		cha.setParameter("SERIE_FORMAT_1","0");
			
		cha.setParameter("SERIE_LINKS_1","http://www.java4less.com|http://www.java4less.com|http://www.java4less.com|http://www.java4less.com|http://www.java4less.com");
				
		cha.setParameter("CHART_TRIGGER_EVENTS","true");			

		System.out.println("Building chart ...");

		Chart c=cha.build(false,false);		
		chartCanvas.setChart(c);
		this.loader=cha;
		
		System.out.println("Build ok");

	}

	
	public void loadChartFromFile(String filename) {
	   
	   System.out.println("Loading "+filename);
	   
	    // stop previous updater thread
	   
	    chartCanvas.getChart().stopUpdater();
	   
		ChartLoader cha=new ChartLoader();			
		cha.loadFromFile(this.getClass().getResourceAsStream("/"+filename),true);
		this.loader=cha;
		System.out.println("Building chart ...");
		Chart c=cha.build(false,false);			
		chartCanvas.setChart(c);
		
		chartCanvas.getChart().setSize(chartCanvas.getPreferredWidth(),chartCanvas.getPreferredHeight());
		
		// set clicked point listener
		if (filename.equalsIgnoreCase("lineChart.txt")) {
			c.addChartListener(chartAdapter);
			c.activateSelection=true;
		}
		
		// set listener for drill down example
		if (filename.equalsIgnoreCase("PieDrillDown.txt")) {
			c.addChartListener(chartAdapterDrillDown);
			c.activateSelection=true;				
		}
		
		// set listener for realtime update example
		if (filename.equalsIgnoreCase("barChart3D.txt")) c.addChartListener(chartAdapter);				
		if (filename.equalsIgnoreCase("realtime.txt")) c.addChartListener(chartAdapterRealtime);
	
			
		chartCanvas.repaintChart();
		
		System.out.println("Build ok");
		
		// real time update example, start update thread
		if ((filename.equalsIgnoreCase("realtime.txt")) || (filename.equalsIgnoreCase("barChart3D.txt")))  c.startUpdater();			

		
	}
	


	
	public void commandAction(Command arg0, Displayable arg1) {
		currentExample++;
		currentExample=currentExample % (examples.length+1);
		
		if (currentExample==0) {
			createDefaultChart();
			chartCanvas.getChart().setSize(chartCanvas.getPreferredWidth(),chartCanvas.getPreferredHeight());
			
			chartCanvas.repaintChart();

		}
		else loadChartFromFile(examples[currentExample-1]);
		
		// load example
		System.out.println("Command click ");
		
	}
	
	
	/**
	 * this method creates realtime data for the realtime example every 2 seconds
	 *
	 */
   private void createRealtimedata(ChartLoader loader) {
		//	create chart

		//	set initial valu of the X Axis based on the time
		java.util.Date now=java.util.Calendar.getInstance().getTime();
				
		loader.setParameter("XAXIS_INITIAL_DATE",Formats.formatDate(now,"dd/MM/yyyy hh:mm:ss"));

		//	create random data based on the time
		java.util.Calendar cal=java.util.Calendar.getInstance();
		String data1="";
		String data2="";
		for (int i=0;i<9;i++) {
			cal.setTime(new Date(cal.getTime().getTime()-2000));
			if (data1.length()>0) data1="|" + data1;
			data1=""+cal.get(java.util.Calendar.SECOND)+ data1;
			if (data2.length()>0) data2="|" + data2;
			data2=""+(cal.get(java.util.Calendar.SECOND)/6)+ data2;		
		}

		loader.setParameter("SERIE_DATA_1",data1);
		loader.setParameter("SERIE_DATA_2",data2);
		

   }
	

}
